//
//  ZYComposePictureView.swift
//  CZ29WeiboZYH
//
//  Created by 沐颜澈 on 16/7/4.
//  Copyright © 2016年 muyanche. All rights reserved.
//

import UIKit

//cell的可重用标识
private let pictureViewCellId = "pictureViewCellId"

class ZYComposePictureView: UICollectionView {
    
    //告知外界弹出相册
    var composePictureViewClosure:(()->())?
    
    //保存图片的数组
    var imageList:[UIImage] = [UIImage]()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        
        setupUI()
        
        
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // MARK: - 供外界调用的方法
    func addImages(image:UIImage) {
    
        //imageList.append(image)
        imageList.insert(image, atIndex: 0)
        if imageList.count > 9 {
            //如果大于九张图片的话就 删除最后一张
            imageList.removeLast()
        
        }
        reloadData()
    }
    
    
     //MARK: - 设置UI
    private func setupUI() {
        
        backgroundColor = UIColor.whiteColor()
        
        //注册cell
        registerClass(CZComposePictureViewCell.self, forCellWithReuseIdentifier: pictureViewCellId)
        
        //设置代理方法
        dataSource = self
        delegate = self
        // 设置layout
        let layout =  collectionViewLayout as! UICollectionViewFlowLayout
        
         let itemMargin: CGFloat = 5
        let cellWH = (SCREENW - 20 - itemMargin*2)/3
        
        // 设置item
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        // 设置垂直和水平间距
        layout.minimumInteritemSpacing = itemMargin
        layout.minimumLineSpacing = itemMargin
        
        
    }

    
}

extension ZYComposePictureView: UICollectionViewDataSource, UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        return imageList.count
        
        let count = imageList.count
        if count == 0 || count == 9 {
            return count
        
        } else {
        
            return imageList.count + 1
        }
        
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureViewCellId, forIndexPath: indexPath) as! CZComposePictureViewCell
        
        //cell.backgroundColor = RandomColor()
        //cell.image = imageList[indexPath.item]
        
        // 给cell设置加号
        if imageList.count ==  indexPath.item {
            cell.image = nil
        }else{
            cell.image = imageList[indexPath.item]
        }
        
        //实现闭包  2
        cell.deleteButtonClosure = {
            
            //删除数组的指定元素
            self.imageList.removeAtIndex(indexPath.item)
            
            //隐藏配图
            if self.imageList.count == 0 {
                self.hidden = true
            }
            //刷新UI
            self.reloadData()
            
        }
        
        return cell
    }
    
    //一点击弹出相册,点击cell的事件方法
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        
        if imageList.count == indexPath.item {
            
            print("点击加号");
            composePictureViewClosure?()
            
        
        }
        
        
    }
}


//自定义cell
class CZComposePictureViewCell: UICollectionViewCell {
    
    //声明删除按钮的闭包  1
    var deleteButtonClosure:(()->())?
    
    //供外界给cell赋值
    var image:UIImage? {
        didSet {
        
            //bgImageView.image = image
            if image == nil {
                bgImageView.image = UIImage(named: "compose_pic_add")
                bgImageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                
                //7.4
                //隐藏删除按钮
                deleteButton.hidden = true
                
            } else {
                
                bgImageView.image = image
                bgImageView.highlightedImage = nil
                
                //显示删除按钮
                deleteButton.hidden = false
            
            }
            
        }
    
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //删除按钮的监听事件
    @objc private func deleteBtnClick() {
        
        //print("删除按钮点击")
        //调用执行闭包    3
        deleteButtonClosure?()
    
    }
    
    //MARK: - 设置视图
    private func setupUI() {
    
        backgroundColor = RandomColor()
        
        //添加控件
        contentView.addSubview(bgImageView)
        //7.4---------
        contentView.addSubview(deleteButton)
        
        
        //添加约束
        bgImageView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        //7.4设置约束
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView)
            make.trailing.equalTo(contentView)
            
        }
        
    }
    
    //懒加载控件
    private lazy var bgImageView: UIImageView = UIImageView()
    
    //7.4 ========= 删除按钮
    private lazy var deleteButton: UIButton = {
        
        let button = UIButton()
        //给button添加点击事件
        button.addTarget(self, action: "deleteBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        
        return button
    
    }()

}
































